import socket
import json
import os
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)

sock.bind(("", 19999))

def getJsonData(path):
    """获取json文件"""
    try:
        with open(path, 'r',encoding='utf-8') as json_file:
            data = json_file.read()
            result = json.loads(data)
    except:
        try:
            with open(path, 'r',encoding='gbk') as json_file:
                data = json_file.read()
                result = json.loads(data)
        except:
            print("json文件读取失败")
            return None
    return result

def getContentPath(path):
    """获取内容浏览器路径"""
    dirlist = []
    textlist = []
    nodelist = []
    if os.path.isdir(path) == True:
        for dir in os.listdir(path):#获取路径下所有文件名/文件夹名
            if os.path.isdir(path+"/"+dir):
                dirlist.append(dir)
                pass#文件夹
            elif os.path.isfile(path+"/"+dir):
                if dir[-5:] != ".json":
                    continue
                data = getJsonData(path+"/"+dir)
                if data["type"]=="QHoudiniTextWidget":
                    textlist.append(dir[:-5])
                if data["type"]=="QHoudiniNodeWidget":
                    nodelist.append(dir[:-5])
                pass#json文件
    return dirlist,textlist,nodelist,path

def runNode(path):
    """运行节点代码生成节点"""
    path = path# + ".json"
    if os.path.exists(path) == False:
        return
    result = getJsonData(path)
    try:
        exec(result["data"])
    except:pass

class AndroidServer(QThread):
    porg = Signal(object)#进度条事件
    def __init__(self,parent=None):
        super().__init__(parent)

    def run(self):
        #print("安卓服务器开启")
        while True:
            recv_data = sock.recvfrom(1024*10)
            text = recv_data[0].decode(encoding='UTF-8')
            clientdata = json.loads(text)
            #print(clientdata)
            if clientdata["pawn"] == "client":
                #print("准备发送数据：")
                if clientdata["command"] == "runNode":
                    runNode(clientdata["path"] + ".json")
                elif clientdata["command"] == "getData":
                    if clientdata["path"] == "":
                        dirlist,textlist,nodelist,path = getContentPath(__file__[:-16] + "/data/ContentBrowser/")
                    else:
                        dirlist,textlist,nodelist,path = getContentPath(clientdata["path"])
                    data = {"pawn": "server","command": "getData", "path": path, "dirlist": dirlist, "textlist": textlist, "nodelist": nodelist}
                    data2 = json.dumps(data)
                    sock.sendto(data2.encode(), ("255.255.255.255", 19999))
                elif clientdata["command"] == "readBook":
                    result = getJsonData(clientdata["path"]+".json")
                    result = result["data"]
                    qtext = QTextEdit()
                    qtext.setHtml(result)
                    textdata = qtext.toPlainText()
                    data = {"pawn": "server","command": "readBook", "bookdata": textdata}
                    data2 = json.dumps(data)
                    sock.sendto(data2.encode(), ("255.255.255.255", 19999))